package org.ragdollcat.first.manager.disruptor;

import cn.hutool.core.util.ObjUtil;
import com.lmax.disruptor.WorkHandler;
import org.ragdollcat.first.exception.ErrorCode;
import org.ragdollcat.first.exception.ThrowUtils;
import org.ragdollcat.first.manager.websocket.PictureEditHandler;
import org.ragdollcat.first.manager.websocket.PictureEditRequestMessage;
import org.ragdollcat.first.model.entity.User;
import org.ragdollcat.first.model.enums.PictureEditMessageTypeEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

/**
 * 事件处理
 */
@Component
public class EditPictureWorkHandler implements WorkHandler<EditPictureDisruptorEvent> {

    @Resource
    private PictureEditHandler pictureEditHandler;

    /**
     * 处理消息
     * @param editPictureDisruptorEvent
     * @throws Exception
     */
    @Override
    public void onEvent(EditPictureDisruptorEvent editPictureDisruptorEvent) throws Exception {
        WebSocketSession session = editPictureDisruptorEvent.getSession();
        Long pictureId = editPictureDisruptorEvent.getPictureId();
        User user = editPictureDisruptorEvent.getUser();
        PictureEditRequestMessage pictureEditRequestMessage = editPictureDisruptorEvent.getPictureEditRequestMessage();


        String type = pictureEditRequestMessage.getType();
        String editAction = pictureEditRequestMessage.getEditAction();

        PictureEditMessageTypeEnum enumByValue = PictureEditMessageTypeEnum.getEnumByValue(type);
        ThrowUtils.throwIf(ObjUtil.isEmpty(enumByValue), ErrorCode.PARAMS_ERROR, "消息类型不合理！");

        //处理各自的消息类型
        switch (enumByValue) {
            case ENTER_EDIT:
                pictureEditHandler.handlerEnter(user, pictureId);
                break;
            case EXIT_EDIT:
                pictureEditHandler.handlerExit(user, pictureId);
                break;
            case EDIT_ACTION:
                pictureEditHandler.handlerEdit(user, pictureId, session, editAction);
                break;
            default:
                break;
        }

    }
}
